<?php
/**
 * Created by PhpStorm.
 * User: MSQ
 * Date: 2021/9/24
 * Time: 14:27
 */

namespace App\Utils;




use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Common
{
    public static $screenJwtKey = 'screen_jwt_key';

    /**
     * 生成随机数
     *
     * @param int $count 长度
     * @param string $chars 随机字符串【不填，则默认】
     * @param int $unique 随机字符串是否唯一【1是、0否】
     * @return array|string
     */
    public static function getRandomAuthKey(int $count = 6, string $chars='', int $unique = 0)
    {
        $chars = $chars ? $chars : '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        if ($unique) {
            $tmp = range(0, strlen($chars)-1);
            shuffle($tmp);
            $keys = array_slice($tmp, 0, $count);
            unset($tmp);
        } else {
            $keys = array_rand(range(0, strlen($chars)-1), $count);
        }

        $buff = array();
        foreach($keys as $value) {
            $buff[] = substr($chars, $value, 1);
        }

        return implode('', $buff);
    }

    /**
     * 解析message->content【过滤配置url】
     * @param string $content
     * @param string|null $fileUrl
     * @param string|null $thumbUrl
     * @return string
     */
    public static function formatMessageContent(string $content, ?string $fileUrl = null, ?string $thumbUrl = null): string
    {
        $wxid = '';
        $newContent = json_decode($content, true);
        if (is_array($newContent) === false) {
            $contentArr = explode(':', $newContent, 2);
            if (count($contentArr) < 2) {
                return FileUtil::getFileUrlPath($content) ?: $content;
            }
            $wxid = $contentArr[0].':';
            $newContent = json_decode($contentArr[1], true);
            if (is_array($newContent) === false) {
                return FileUtil::getFileUrlPath($content) ?: $content;
            }
        }

        if (isset($newContent['Thumb'])) {
            $newContent['Thumb'] = FileUtil::getFileUrlPath($newContent['Thumb']) ?: $newContent['Thumb'];
        }
        if (!is_null($thumbUrl)) {
            $newContent['Thumb'] = FileUtil::getFileUrlPath($thumbUrl) ?: $thumbUrl;
        }
        if (!is_null($fileUrl)) {
            $newContent['fileUrl'] = FileUtil::getFileUrlPath($fileUrl) ?: $fileUrl;
        }

        return $wxid.json_encode($newContent);
    }

    /**
     * 解析消息内容【添加配置url】
     * @param string $content
     * @return string
     */
    public static function parseMessageContent(string $content): string
    {
        $wxid = '';
        $newContent = json_decode($content, true);
        if (is_array($newContent) === false) {
            $contentArr = explode(':', $newContent, 2);
            if (count($contentArr) < 2) {
                return FileUtil::getFileConfigUrl($content);
            }
            $wxid = $contentArr[0].':';
            $newContent = json_decode($contentArr[1], true);
            if (is_array($newContent) === false) {
                return FileUtil::getFileConfigUrl($content);
            }
        }

        if (isset($newContent['fileUrl'])) {
            $newContent['fileUrl'] = FileUtil::getFileConfigUrl($newContent['fileUrl']);
        }
        if (isset($newContent['Thumb'])) {
            $newContent['Thumb'] = FileUtil::getFileConfigUrl($newContent['Thumb']);
        }
        return $wxid.json_encode($newContent);
    }



    /**
     * 大屏账号
     * @return \string[][]
     */
    public static function getProjectAccount(int $projectId): array
    {
        $map = [
            3 => [// 北大
                'account' => 'admin',
                'password' => 'jgwl123456',
            ]
        ];

        return $map[$projectId] ?? [];
    }

    /**
     * 加密生成token
     * @param int $projectId
     * @param string $account
     * @param string $password
     * @return string
     */
    public static function encodeToken(int $projectId, string $account, string $password): string
    {
        $key = self::$screenJwtKey;
        $payload = [
            "project_id" => $projectId,
            "account" => $account,
            "password" => $password,
        ];

        /**
         * IMPORTANT:
         * You must specify supported algorithms for your application. See
         * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
         * for a list of spec-compliant algorithms.
         */
        $jwt = JWT::encode($payload, $key, 'HS256');

        return $jwt;
    }

    /**
     * 解析token
     * @param string $token
     * @return array|false
     */
    public static function decodeToken(string $token)
    {
        try {
            $key = self::$screenJwtKey;
            $decoded = JWT::decode($token, new Key($key, 'HS256'));
        } catch (\Exception $e) {
            return false;
        }

        return (array)$decoded;
    }

    /**
     * curl  https请求
     *
     * @param $url
     * @param null $data
     * @return bool|string
     * @author chenyuebin
     */
    public static function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
